import React from "react";

import PageContent from '../../PageContent'

import { ajax ,showResultMessage,isNull,isNotNull,setStoreItem,getStoreItem} from '../../common';

import { Link } from 'react-router-dom';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UIFormView from '../../uicomponents/UIFormView';

import UIToolbar from '../../uicomponents/UIToolbar';

import ImportProductUITreePanel from './ImportUIDataFilePanel';

import ExportProductUITreePanel from './ExportUIDataFilePanel';

/** 
 *产品UI树管理
*/
export default class ProductUITreeManageApp extends React.Component {

    state = {
		treeSearchValues : getStoreItem('uiTreeSearchValues',{}),
	}

	onTreeSearchValueChange = (values) => {
		this.setState({treeSearchValues : values});
		setStoreItem('uiTreeSearchValues',values);
	}

	render() {

        /**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUITreeListPanel {...props} 
						treeSearchValues={this.state.treeSearchValues} 
						onTreeSearchValueChange={this.onTreeSearchValueChange}
						key="UITreeList" 
						
						/>
						);
				}
			},
			'/editUITreeNodes': {
				text: '编辑树节点',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUITreeNodeListPanel {...props} key="editTreeNodes" />);
				}
			},
			'/editUITreeNodes/editUITreeNodeBuilders': {
				text: '编辑树节点构造器',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUITreeNodeBuilderPanle {...props} key="configTreeNodeBuilders" />);
				}
			},
			'/importDataFiles': {
				text: '导入UI树',
				icon: 'sign-in-alt',
                getComponent: (owner, props) => {
                    return <ImportProductUITreePanel {...props} importURL="PRODUCT/UI/import/importUITreeFile/" pageTitle="导入UI树" key="importTrees"/>;
                }
			},
			'/exportDataFiles': {
				text: '导出UI树',
				icon: 'sign-out-alt',
                getComponent: (owner, props) => {
                    return <ExportProductUITreePanel {...props} exportURL="PRODUCT/UI/export/exportUITreeFile/" pageTitle="导出UI树" key="exportTrees"/>;
                }
			},
			
        }

		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap}>
			</PageContent>
		);
	}
}



/** 
 * 产品UI树列表
*/
class ProductUITreeListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
            formTitle: '',
		}
    }

	actionHandler = (actionEvent) => {

		const { selectTreeIds, treeListRef, treeFormRef } = this;

		return {
			refresh : () => {
				treeListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增产品UI树'});
				setTimeout(() => {
					treeFormRef.openModal(() => {
						const initParams = getStoreItem('uiTreeSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							treeFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑产品UI树' });
				setTimeout(() => {
					treeFormRef.openModal(() => {
						treeFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectTreeIds;
				}

				ajax('PRODUCT/UI/productUITree/batchDelete', { ids: selectedIds }, (data) => {
					treeListRef.loadData();
				});
			},
			doSave : () => {
				treeFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUITree/save', formData, (data) => {
						treeFormRef.closeModal();
						treeListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
            ref: (inst) => { this.treeListRef = inst },
            history : this.props.history,
			actionHandler: this.actionHandler,
			title : "UI树",
			extra : (<UIToolbar history={this.props.history} actionGroupId="productUIDataPanelActionGroup" actionHandler={this.actionHandler}/>),
			actionGroupId: 'productUITreeListActionGroup',
			rowActionGroupId: 'productUITreeRowActionGroup',
			tableConfigId: 'productUITreeTable',
			dataUrl: 'PRODUCT/UI/productUITree/query',
			selectMode: 'multi',
            searchFormId: 'productUITreeSearchForm',
            initSearchValues : this.props.treeSearchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectTreeIds = selectRowKeys;
				}
            ,
            onSearchData : (changedValues) => {
				
				if(this.props.onTreeSearchValueChange){
					this.props.onTreeSearchValueChange(changedValues)
				}
			}
		};

		const treeFormProps = {
			ref: (inst) => { this.treeFormRef = inst },
			formConfigId: 'productUITreeForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...treeFormProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 编辑树节点
 */
class EditProductUITreeNodeListPanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
			treeNode : null,
		}
	}
	
	componentDidMount(){
		this.tree = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.tree.code +   ']节点'});
		this.loadTreeNodes(this.tree.id);
	}

    loadTreeNodes = (treeId) => {
		
        this.treeNodeListRef.loadData({treeId : treeId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds,treeNodeEditFormRef, treeNodeListRef,treeNodeBuilderViewRef,tree } = this;

		return {
			refresh : () => {
				treeNodeListRef.loadData({treeId :tree.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加树节点'});
				
				setTimeout(() => {
					treeNodeEditFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑树节点',treeNode : actionEvent.params  });
				
				setTimeout(() => {
					treeNodeEditFormRef.openModal(() => {
						treeNodeEditFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUITreeNode/batchDelete', { ids: selectedIds }, (data) => {
					treeNodeListRef.loadData({treeId :tree.id});
				});
			},
			doSave : () => {

				if(treeNodeEditFormRef.isOpend()){
					treeNodeEditFormRef.getFormData((formData) => {
						formData.treeId = tree.id;
						ajax('PRODUCT/UI/productUITreeNode/save', formData, (data) => {
							treeNodeEditFormRef.closeModal();
							treeNodeListRef.loadData({treeId :tree.id});
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}
								
			},
		};
	}

	render () {

		const tableProps = {
			bordered : false,
			history : this.props.history,
			title : this.state.pageTitle,
			ref: (inst) => { this.treeNodeListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUITreeNodeListActionGroup',
			rowActionGroupId: 'productUITreeNodeRowActionGroup',
			tableConfigId: 'productUITreeNodeTable',
			dataUrl: 'PRODUCT/UI/productUITreeNode/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView formConfigId="productUITreeNodeForm" 
					inPop={true} destroyOnClose={true} title={this.state.formTitle} ref={(inst) => this.treeNodeEditFormRef = inst} 
					actionGroupId={'saveActionGroup'} actionHandler={this.actionHandler}
				/>
			</UIDataTableView>
		);
	}
}

/**
 * 编辑节点构造器
 */
class EditProductUITreeNodeBuilderPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
			treeNodeBuilder : null,
		}
	}
	
	componentDidMount(){
		this.treeNode = this.props.location.state;
		ajax('PRODUCT/UI/productUITree/getById',{id : this.treeNode.treeId},(data) => {
			this.setState({pageTitle : '编辑[' + this.treeNode.code +   ']节点构造器',tree : data});
			this.loadTreeNodeBuilders(this.treeNode.id);
		});
		
	}

    loadTreeNodeBuilders = (treeNodeId) => {
		
        this.treeNodeBuilderListRef.loadData({treeNodeId : treeNodeId});
	}
	
	actionHandler = (actionEvent) => {

		const { selectIds,treeNodeBuilderEditFormRef, treeNodeBuilderListRef,treeNode } = this;

		return {
			refresh : () => {
				this.loadTreeNodeBuilders(treeNode.id);
			},
			addNew : () => {
				this.setState({ formTitle: '添加树节点构造器'});
				
				setTimeout(() => {
					treeNodeBuilderEditFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑树节点构造器',treeNodeBuilder : actionEvent.params  });
				
				setTimeout(() => {
					treeNodeBuilderEditFormRef.openModal(() => {
						treeNodeBuilderEditFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUITreeNodeBuilder/batchDelete', { ids: selectedIds }, (data) => {
					this.loadTreeNodeBuilders(treeNode.id);
				});
			},
			doSave : () => {

				if(treeNodeBuilderEditFormRef.isOpend()){
					treeNodeBuilderEditFormRef.getFormData((formData) => {
						formData.nodeId = treeNode.id;
						ajax('PRODUCT/UI/productUITreeNodeBuilder/save', formData, (data) => {
							treeNodeBuilderEditFormRef.closeModal();
							this.loadTreeNodeBuilders(treeNode.id);
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}
								
			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < treeNodeBuilderListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUITreeNodeBuilder/save',rowData,(data) => {
						this.loadTreeNodeBuilders(treeNode.id);
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUITreeNodeBuilder/save',rowData,(data) => {
						this.loadTreeNodeBuilders(treeNode.id);
					});
				}
			},
			
		};
	}

	render(){

		const {tree} = this.state;

		const tableProps = {
			bordered : false,
			history : this.props.history,
			title : this.state.pageTitle,
			ref: (inst) => { this.treeNodeBuilderListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUITreeNodeBuilderListActionGroup',
			rowActionGroupId: 'productUITreeNodeBuilderRowActionGroup',
			tableConfigId: 'productUITreeNodeBuilderTable',
			dataUrl: 'PRODUCT/UI/productUITreeNodeBuilder/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		return (
			<UIDataTableView extra={<Link to={{pathname : '/editUITreeNodes',state : tree}}>返回</Link>} {...tableProps}>
				<UIFormView formConfigId="productUITreeNodeBuilderForm" 
					inPop={true} destroyOnClose={true} title={this.state.formTitle} ref={(inst) => this.treeNodeBuilderEditFormRef = inst} 
					actionGroupId={'saveActionGroup'} actionHandler={this.actionHandler}
				/>
			</UIDataTableView>
		);
	}
}